import { defineStore } from 'pinia'

export interface RecordingState {
  // 是否正在录制
  isRecording: boolean
  // 录制时间
  recordingTime: number
  // 录制时长
  recordingDuration: number
  // 录制开始时间
  recordingStartTime: number
  // 录制结束时间
  recordingEndTime: number
  // 录制计时器
  recordingInterval: NodeJS.Timeout | null
  // 录制流
  recordingStream: MediaStream | null
  // 媒体录制器
  mediaRecorder: MediaRecorder | null
  // 录制的数据块
  recordedChunks: Blob[]
  // 录制的视频URL
  recordedVideoUrl: string | null
  // 录制设置
  settings: {
    // 是否录制鼠标
    captureMouse: boolean
    // 是否录制音频
    captureAudio: boolean
    // 是否录制系统音频
    captureSystemAudio: boolean
    // 是否录制摄像头
    captureCamera: boolean
    // 视频质量
    videoQuality: 'high' | 'medium' | 'low'
    // 录制区域类型
    captureType: 'display' | 'window' | 'region'
    // 自定义录制区域
    captureRegion: {
      enabled: boolean
      x: number
      y: number
      width: number
      height: number
      devicePixelRatio?: number
    }
  }
}

export const useRecordingStore = defineStore('recording', {
  state: (): RecordingState => ({
    isRecording: false,
    recordingTime: 0,
    recordingDuration: 0,
    recordingStartTime: 0,
    recordingEndTime: 0,
    recordingInterval: null,
    recordingStream: null,
    mediaRecorder: null,
    recordedChunks: [],
    recordedVideoUrl: null,
    settings: {
      captureMouse: true,
      captureAudio: true,
      captureSystemAudio: false,
      captureCamera: false,
      videoQuality: 'high',
      captureType: 'window',
      captureRegion: {
        enabled: false,
        x: 0,
        y: 0,
        width: 640,
        height: 480
      }
    }
  }),
  getters: {
    recordingTimeFormatted: (state) => {
      // 格式化时间
      const hours = Math.floor(state.recordingTime / 3600)
      const minutes = Math.floor((state.recordingTime % 3600) / 60)
      const seconds = state.recordingTime % 60
      // 保存两位
      const hoursFormatted = hours.toString().padStart(2, '0')
      const minutesFormatted = minutes.toString().padStart(2, '0')
      const secondsFormatted = seconds.toString().padStart(2, '0')
      // 如果小时为0，则不显示小时
      if (hours === 0) {
        return `${minutesFormatted}:${secondsFormatted}`
      }
      return `${hoursFormatted}:${minutesFormatted}:${secondsFormatted}`
    },
    isStreamAvailable: (state) => !!state.recordingStream && state.recordingStream.active,
    isRecorderActive: (state) => !!state.mediaRecorder && state.mediaRecorder.state === 'recording'
  },
  actions: {
    startRecording() {
      this.isRecording = true
      this.recordingTime = 0
      this.recordingStartTime = Date.now()
      this.recordedChunks = [] // 清空之前的录制数据
      this.recordingInterval = setInterval(() => {
        this.recordingTime = Math.floor((Date.now() - this.recordingStartTime) / 1000)
      }, 1000)
    },
    stopRecording() {
      this.isRecording = false
      this.recordingEndTime = Date.now()
      this.recordingDuration = this.recordingEndTime - this.recordingStartTime
      if (this.recordingInterval) {
        clearInterval(this.recordingInterval)
        this.recordingInterval = null
      }

      // 释放资源
      this.releaseMediaResources()
    },
    setMediaRecorder(mediaRecorder: MediaRecorder) {
      this.mediaRecorder = mediaRecorder
    },
    setRecordingStream(stream: MediaStream) {
      this.recordingStream = stream
    },
    addRecordedChunk(chunk: Blob) {
      this.recordedChunks.push(chunk)
    },
    getRecordedBlob() {
      if (this.recordedChunks.length === 0) return null

      return new Blob(this.recordedChunks, {
        type: 'video/webm'
      })
    },
    createVideoUrl() {
      const blob = this.getRecordedBlob()
      if (!blob) return null

      // 释放之前的URL资源
      if (this.recordedVideoUrl) {
        URL.revokeObjectURL(this.recordedVideoUrl)
      }

      this.recordedVideoUrl = URL.createObjectURL(blob)
      return this.recordedVideoUrl
    },
    releaseMediaResources() {
      // 停止媒体录制器
      if (this.mediaRecorder && this.mediaRecorder.state !== 'inactive') {
        this.mediaRecorder.stop()
      }

      // 停止媒体流的所有轨道
      if (this.recordingStream) {
        this.recordingStream.getTracks().forEach((track) => {
          track.stop()
        })
        this.recordingStream = null
      }

      this.mediaRecorder = null
    },
    updateSettings(settings: Partial<RecordingState['settings']>) {
      this.settings = { ...this.settings, ...settings }
    },
    reset() {
      this.releaseMediaResources()
      this.isRecording = false
      this.recordingTime = 0
      this.recordingDuration = 0
      this.recordingStartTime = 0
      this.recordingEndTime = 0
      this.recordedChunks = []

      // 释放视频URL
      if (this.recordedVideoUrl) {
        URL.revokeObjectURL(this.recordedVideoUrl)
        this.recordedVideoUrl = null
      }
    }
  }
})

export function useRecordingStoreHook() {
  return useRecordingStore()
}
